package com.study.config;

import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.study.vo.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;

/**
 * RestTemplate 在Sentinel限流或者异常时的兜底方式
 */
@Slf4j
public class RestTemplateExceptionUtil {

    //限流后的处理方法
    public static SentinelClientHttpResponse handlerBlock(
            HttpRequest request,
            byte[] body,
            ClientHttpRequestExecution execution,
            BlockException ex
    ) {

        log.error("Handler restTemplate block exception :[{}],[{}]",
                request.getURI(),ex.getClass().getCanonicalName());

        return new SentinelClientHttpResponse(
                JSON.toJSONString((new JwtToken("study-block")))
        );
    }

    //异常降级之后的处理方法
    public static SentinelClientHttpResponse handlerFallback(
            HttpRequest request,
            byte[] body,
            ClientHttpRequestExecution execution,
            BlockException ex
    ) {

        log.error("Handler restTemplate Fallback exception :[{}],[[]]",
                request.getURI(),ex.getClass().getCanonicalName());

        return new SentinelClientHttpResponse(
                JSON.toJSONString((new JwtToken("study-block")))
        );
    }

}
